package com.example.douyin.controller.qianduoduo;

import com.alibaba.fastjson.JSON;
import com.example.douyin.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

@RestController
@Slf4j
@RequestMapping(("duo"))
public class DuoController {
    @Resource
    private RestTemplate restTemplate;


    @GetMapping("test")
    public String test(){
        String queryUrl = "https://cambridge.didavsh.cn/kns/request/CustomizeOperate.aspx?p=0";
        MultiValueMap<String, String> loginMap = new LinkedMultiValueMap<>();
        loginMap.add("formfilenames", "CJFDLAST2016!ZZYZ201608023!4!8,CJFDLAST2021!YWPJ202109001!5!8");
        HttpHeaders httpHeaders = getHttpHeaders();
        httpHeaders.set("Cookie","");
        HttpEntity<MultiValueMap<String, String>> loginEntity = new HttpEntity<>(loginMap, httpHeaders);
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_XML, MediaType.APPLICATION_PROBLEM_XML));
        restTemplate.getMessageConverters().add(converter);
        String str = restTemplate.postForObject(queryUrl, loginEntity, String.class);
        System.out.println(str);
        return str;

    }
    @GetMapping("test2")
    public String test2(){
        String queryUrl = "https://cambridge.didavsh.cn/kns/request/SearchHandler.ashx?action=&NaviCode=*&ua=1.21&PageName=ASP.brief_result_aspx&DbPrefix=SCDB&DbCatalog=中国学术文献网络出版总库&ConfigFile=SCDB.xml&db_opt=CJFQ,CDFD,CMFD,CPFD,IPFD,CCND,CCJD&base_special1=%&magazine_special1=%&txt_1_sel=SU&txt_1_value1=感冒&txt_1_value2=指南&txt_1_relation=#CNKI_AND&txt_1_special1==&his=0&__=Thu Jul 14 2022 11:33:13 GMT+0800 (中国标准时间)";
        HttpHeaders httpHeaders = getHttpHeaders();
        httpHeaders.set("Cookie","Ecp_ClientId=7220713180102268053; SID_epub=025126011; sitetoken=35710; cnkiUserKey=0fd378de-414a-8168-8819-417b8015ff33; DisplaySave=13; Ecp_IpLoginFail=220713103.163.47.188, 43.154.184.177; ASP.NET_SessionId=qbqjqj4ryrfxi0xr1jmghvry");
        httpHeaders.set("Referer","https://cambridge.didavsh.cn/kns/brief/result.aspx?dbprefix=scdb");
        httpHeaders.set("sec-ch-ua","\".Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"103\", \"Chromium\";v=\"103\"");
        httpHeaders.set("sec-ch-ua-mobile","?0");
        httpHeaders.set("sec-ch-ua-platform","\"Windows\"");
        httpHeaders.set("Sec-Fetch-Dest","empty");
        httpHeaders.set("Sec-Fetch-Mode","cors");
        httpHeaders.set("Sec-Fetch-Site","same-origin");
        HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
        // get请求如果想要设置请求头，需要使用exchange方法，因为getForxx方法不支持请求头
        ResponseEntity<String> exchange = restTemplate.exchange(queryUrl, HttpMethod.GET, httpEntity, String.class);
        System.out.println(JSON.toJSONString(exchange));

        return exchange.getBody();

    }

    @PostMapping("gotoBuy")
    public List<DcAppOrderPayDetail> gotoBuy(DcAppGotoByVo dcAppGotoByVo) {
        List<DcAppOrderPayDetail> list = new ArrayList<>();
        if (StringUtils.isEmpty(dcAppGotoByVo.getUserName()) || StringUtils.isEmpty(dcAppGotoByVo.getPassword())) {
            log.info("用户名或者密码不能为空");
            return list;
        }
        String loginUrl = "http://www.dianchouapp.com/app/user/loginNormal";
        MultiValueMap<String, String> loginMap = new LinkedMultiValueMap<>();
        loginMap.add("userName", dcAppGotoByVo.getUserName());
        loginMap.add("password", dcAppGotoByVo.getPassword());
        HttpHeaders httpHeaders = getHttpHeaders();
        HttpEntity<MultiValueMap<String, String>> loginEntity = new HttpEntity<>(loginMap, httpHeaders);
        DcAppLoginVo dcAppLoginVo = restTemplate.postForObject(loginUrl, loginEntity, DcAppLoginVo.class);
        log.info("----登录出参：{}", dcAppLoginVo);
        String tokenId = "";
        if (Objects.nonNull(dcAppLoginVo) && "200".equals(dcAppLoginVo.getErrorCode())) {
            DcAppLoginDetailVo detail = dcAppLoginVo.getDetail();
            tokenId = detail.getTokenId();

            MultiValueMap<String, String> searchListMap = new LinkedMultiValueMap<>();
            searchListMap.add("commodityName", dcAppGotoByVo.getCommodityName());
            searchListMap.add("businessType", dcAppGotoByVo.getBusinessType());
            String pageListUrl = "http://www.dianchouapp.com/app/shopBuy/listPage?tokenId=" + tokenId;
            HttpEntity<MultiValueMap<String, String>> searchListEntity = new HttpEntity<>(searchListMap, httpHeaders);
            DcAppPageListVo pageListVo = restTemplate.postForObject(pageListUrl, searchListEntity, DcAppPageListVo.class);
            log.info("----查询列表出参：{}", pageListVo);
            if (Objects.nonNull(pageListVo) && "200".equals(pageListVo.getErrorCode())) {
                DcAppPageListDetailVo pageListVoDetail = pageListVo.getDetail();
                List<DcAppSkuInfoVo> recordList = pageListVoDetail.getRecordList();

                Double setPrice = dcAppGotoByVo.getSetPrice();
                for (DcAppSkuInfoVo dcAppSkuInfoVo : recordList) {
                    // 价格合理，开始下单
                    if (Objects.nonNull(dcAppSkuInfoVo) && dcAppSkuInfoVo.getPrice() < setPrice) {
                        Long buyMainId = dcAppSkuInfoVo.getBuyMainId();
                        String skuDetailUrl = "http://www.dianchouapp.com/app/shopBuy/detail?id=" + buyMainId + "&tokenId=" + tokenId;
                        ResponseEntity<DcAppSkuVo> skuDetailResp = restTemplate.getForEntity(skuDetailUrl, DcAppSkuVo.class);
                        log.info("----查询详情出参：{}", skuDetailResp);
                        DcAppSkuVo body = skuDetailResp.getBody();
                        if (Objects.nonNull(body) && Objects.nonNull(body.getDetail())) {
                            DcAppSkuDetailVo skuDetailVo = body.getDetail();
                            List<DcAppSkuStockInfoVo> skuStockInfoVos = skuDetailVo.getShopBuySpecAndStockVoList();
                            for (DcAppSkuStockInfoVo skuStockInfoVo : skuStockInfoVos) {
                                String buySpecId = skuStockInfoVo.getBuySpecId();
                                Integer stock = skuStockInfoVo.getStock();
                                Double price = skuStockInfoVo.getPrice();
                                if (price < setPrice) {
                                    // 价格合理，拿到下单ID，直接去下单
                                    String gotoBuyUrl = "http://www.dianchouapp.com/app/orderV2/preOrderConfirm?tokenId=" + tokenId;
                                    MultiValueMap<String, String> gotoBuyMap = new LinkedMultiValueMap<>();
                                    String preOrderVo = "{\"ableAppWeixinMini\":\"1\",\"goods\":[{\"buySpecId\":\"" + buySpecId + "\",\"counts\":" +
                                            stock + "}],\"latitude\":0,\"longitude\":0,\"platform\":\"app\",\"proxyOrder\":false,\"reserveId\":0,\"liveRecordId\":\"\"}";
                                    gotoBuyMap.add("preOrderVo", preOrderVo);
                                    HttpEntity<MultiValueMap<String, String>> gotoBuyEntity = new HttpEntity<>(gotoBuyMap, httpHeaders);
                                    DcAppOrderConfirmVo orderConfirmResp = restTemplate.postForObject(gotoBuyUrl, gotoBuyEntity, DcAppOrderConfirmVo.class);
                                    log.info("----去支付出参：{}", orderConfirmResp);
                                    if (Objects.nonNull(orderConfirmResp) && Objects.nonNull(orderConfirmResp.getDetail())) {
                                        DcAppOrderConfirmDetailVo confirmVo = orderConfirmResp.getDetail();
                                        String addressId = confirmVo.getAddressId();
                                        String createOrderVo = "{\"addressId\":\"" + addressId + "\",\"dianchouPayAmount\":0,\"goods\":[{\"buySpecId\":\"" +
                                                buySpecId + "\",\"counts\":" + stock + "}],\"payLater\":false,\"payType\":\"alipay\",\"platSource\":\"ANDROID\"," +
                                                "\"platform\":\"app\",\"proxyOrder\":false,\"receiveType\":\"DELIVERY\",\"reserveId\":0,\"version\":\"1.0\",\"liveRecordId\":\"\"}";
                                        String orderPayUrl = "http://www.dianchouapp.com/app/orderV2/orderPay?tokenId=" + tokenId;
                                        MultiValueMap<String, String> orderPayMap = new LinkedMultiValueMap<>();
                                        orderPayMap.add("createOrderVo", createOrderVo);
                                        HttpEntity<MultiValueMap<String, String>> orderPayEntity = new HttpEntity<>(orderPayMap, httpHeaders);
                                        DcAppOrderPayVo orderPayResp = restTemplate.postForObject(orderPayUrl, orderPayEntity, DcAppOrderPayVo.class);
                                        log.info("----确认支付出参：{}", orderPayResp);
                                        if (Objects.nonNull(orderPayResp) && "200".equals(orderPayResp.getErrorCode()) && Objects.nonNull(orderPayResp.getDetail())) {
                                            DcAppOrderPayDetail payRespDetail = orderPayResp.getDetail();
                                            if (Objects.nonNull(confirmVo.getFarmers())){
                                                List<DcAppOrderConfirmDetailFarmersVo> farmers = confirmVo.getFarmers();
                                                List<DcAppOrderConfirmDetailFarmersGoodsVo> goods = new ArrayList<>();
                                                for (DcAppOrderConfirmDetailFarmersVo farmer : farmers) {
                                                    List<DcAppOrderConfirmDetailFarmersGoodsVo> farmerGoods = farmer.getGoods();
                                                    goods.addAll(farmerGoods);
                                                }
                                                payRespDetail.setGoods(goods);
                                            }
                                            list.add(payRespDetail);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return list;
    }

    private HttpHeaders getHttpHeaders() {
        // 模拟form表单发送请求
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        return httpHeaders;
    }

}
